package com.loong.scala.jsonregex

import java.util.regex.Pattern

import scala.util.parsing.json.{JSON, JSONArray, JSONObject}


/**
  * Created by 梁浩峰 on 2016/9/14 13:47.
  */
class JsonRegexUtils {
  /**
    * 将json字符串中的影响json串格式的字符替换为合法字符，该替换为全部替换
    *
    * @param json
    * @param replaceRegex
    * @param replace
    * @return 替换后的字符串
    */
  def jsonActionAll(json: String, replaceRegex: String, replace: String): String = {
    val r = Pattern.compile(replaceRegex)
    val m = r.matcher(json)
    m.replaceAll(replace)
  }

  /**
    * 将json字符串中的影响json串格式的字符替换为合法字符，该替换为首次匹配到的替换
    *
    * @param json
    * @param replaceRegex
    * @param replace
    * @return 替换后的字符串
    */
  def jsonActionFirst(json: String, replaceRegex: String, replace: String): String = {
    val r = Pattern.compile(replaceRegex)
    val m = r.matcher(json)
    m.replaceFirst(replace)
  }

  def isJsonArray(json: String): Boolean = {
    if (json.startsWith("[") && json.endsWith("]")) {
      true
    } else {
      false
    }
  }


  def jsonRegex(json: String): (String, String, String, String) = {
    if (isJsonArray(json)) {
      val map: Map[String, String] = JSON.parseFull(json) match {
        case Some(List(map: Map[String, String])) => map
        case _ => null
      }
      val send_time = map.get("send_time") match {
        case Some(e) => e.toString
      }
      val send_log_info = map.get("send_log_info") match {
        case Some(e) => e.toString
      }
      val log_level = map.get("log_level") match {
        case Some(e) => e.toString
      }
      val send_log_address = map.get("send_log_address") match {
        case Some(e) => e.toString
      }
      return (send_time,send_log_info,send_log_address, log_level)
    } else {
      null
    }
  }


}

object JsonRegexUtils {
  def apply: JsonRegexUtils = new JsonRegexUtils()

  def jsonActionFirst(json: String, replaceRegex: String, replace: String) = apply.jsonActionFirst(json, replaceRegex, replace)

  def jsonActionAll(json: String, replaceRegex: String, replace: String) = apply.jsonActionAll(json, replaceRegex, replace)

  def jsonRegex(json: String) = apply.jsonRegex(json)
}
